<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-bind="$attrs"
    @open="handlerOpen"
    v-on="$listeners"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色" prop="rid">
        <el-select v-model="form.rid" placeholder="请选择">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button type="primary" @click="submitForm('form')">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { putUserRole } from '@/api/user'
import { getRoles } from '@/api/rights'

const rules = {
  rid: [
    { required: true, message: '请输入用户名称', trigger: 'blur' }
  ]
}

export default {
  name: 'ROLEFORM',
  props: {
    user: {
      type: Object,
      required: true
    },
    cb: {
      type: Function
    }
  },
  data() {
    return {
      form: {
        rid: ''
      },
      rules,
      roles: []
    }
  },
  computed: {
    title() {
      if (this.user.username) {
        return this.user.username + '角色选择'
      } else {
        return '角色选择'
      }
    }
  },
  watch: {
    user: {
      handler(newValue) {
        this.form.rid = newValue.rid || ''
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    handlerOpen() {
      if (this.roles.length < 0) {
        console.log('handlerOpen to getRoles')
        this.getRoles()
      }
      const role = this.roles.find(i => i.roleName === this.user.role_name)
      this.form.rid = role.id
    },
    async getRoles() {
      const res = await getRoles()
      this.roles = res
    },
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const data = {
            id: this.user.id,
            rid: this.form.rid
          }
          await putUserRole(data)
          this.$message({
            message: '更换角色成功',
            type: 'success'
          })
          this.$emit('update:visible', false)
          this.cb && this.cb()
        } else {
          return false
        }
      })
    }
  }
}
</script>
